package com.tiantian.web.controller.compaints;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tiantian.bean.PageBean;
import com.tiantian.cache.user.UserInfoCache;
import com.tiantian.domain.Orderwhisperinformation;
import com.tiantian.domain.OrderwhisperinformationId;
import com.tiantian.domain.Orderwhisperrelationship;
import com.tiantian.domain.Usercomplaints;
import com.tiantian.domain.Usermessages;
import com.tiantian.ret.Result;
import com.tiantian.service.BackstagelogService;
import com.tiantian.service.BusinessUsersService;
import com.tiantian.service.BuyersUsersService;
import com.tiantian.service.OrderWhisperInformationService;
import com.tiantian.service.OrderWhisperRelationshipService;
import com.tiantian.service.UserComplaintsService;
import com.tiantian.service.UserMessagesService;
import com.tiantian.util.CommonConstant;
import com.tiantian.util.PageUtil;
import com.tiantian.web.datatables.DataTableReturn;

/**
 * 申诉管理
 * 
 */
@Controller
@RequestMapping("/complaints")
public class UserComplaintsController {

	public static final Logger LOG = LoggerFactory.getLogger(UserComplaintsController.class);

	@Resource
	private UserComplaintsService userComplaintsService;

	@Resource
	private OrderWhisperInformationService orderInfoServivce;

	@Resource
	private OrderWhisperRelationshipService shipService;

	@Resource
	private UserMessagesService userMessageService;

	@Resource
	private BusinessUsersService businessUserService;

	@Resource
	private BuyersUsersService buyerUserService;
	@Autowired
	private BackstagelogService backstagelogService;

	/**
	 * 申述管理
	 * 
	 * @param tipBuyersNotes
	 * @return
	 */
	@RequestMapping("list")
	public void complaints() {

	}

	/**
	 * 获取申诉信息你数据
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("getList")
	@ResponseBody
	public Object getList(CompaintsVo vo, HttpServletRequest request) {
		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(vo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		List<Map<String, Object>> data = userComplaintsService.list(params, page);
		return new DataTableReturn(page.getDraw(), page.getTotal(), page.getTotal(), data);
	}

	/**
	 * 平台处理状态修改
	 * 
	 * @param buyersUserID
	 * @param raiseCashTime
	 * @return
	 */
	@RequestMapping("/updateStauts")
	@ResponseBody
	public Object updateStauts(@RequestParam Integer status, @RequestParam String complaintsId) {
		String[] ids = StringUtils.split(complaintsId, ",");
		Usercomplaints compaints = null;
		try {
			List<Usercomplaints> list = new ArrayList<>();
			for (int i = 0; i < ids.length; i++) {
				compaints = this.userComplaintsService.get(ids[i]);
				compaints.setAppealsStatus(status);
				//compaints.setPlatformProcessingStatus(status);
				list.add(compaints);
			}
			this.userComplaintsService.save(list);
			if (status.intValue() == 1) {// 跟进
				backstagelogService.log("041", compaints.getOrderId(), true);
			} else {
				backstagelogService.log("042", compaints.getOrderId(), true);
			}

		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("平台状态修改", e);
			if (status.intValue() == 1) {// 跟进
				backstagelogService.log("041", compaints.getOrderId(), false);
			} else {
				backstagelogService.log("042", compaints.getOrderId(), false);
			}
			return new Result<Object>(false, "操作失败");
		}

		return new Result<Object>(true, "操作成功");
	}

	/**
	 * 查看申述进程
	 * 
	 * @param sponsor
	 * @param orderId
	 * @param appealsTime
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/detail")
	public String detail(String complaintsId, ModelMap map) {
		Usercomplaints compaints = this.userComplaintsService.get(complaintsId);
		map.put("compaints", compaints);// 申述内容
		List<Map<String, Object>> pic = this.userComplaintsService.getPic(compaints.getOrderId());
		map.put("pics", pic);// 申述图片
		Map<String, Object> param = new HashMap<>();
		param.put("orderId", compaints.getOrderId());
		param.put("userId1", compaints.getSponsor());
		param.put("userId2", compaints.getOtherUsers());
		List<Map<String, Object>> compaintsInfo = this.orderInfoServivce.getCompaintsInfo(param);
		map.put("compaintsInfo", compaintsInfo);// 申述聊天内容

		map.put("ship", this.shipService.getByOrderId(compaints.getOrderId()));

		return "/complaints/detail";
	}

	/**
	 * 新增申述聊天内容
	 * 
	 * @param status
	 * @param sponsor
	 * @param orderId
	 * @param appealsTime
	 * @return
	 */
	@RequestMapping("/saveComplaintsInfo")
	@ResponseBody
	public Object saveComplaintsInfo(String orderWhisperInfoID, String textContent,String complaintsId) {
		Usercomplaints complaints = null;
		try {
			String sendTime = DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd");
			complaints = this.userComplaintsService.get(complaintsId);
			String otherUserId = null;// 接受人userid
			String sendUserID = UserInfoCache.getCurrentUser().getUserId();
			int sendUserType = 3;
		
			if (complaints.getSponsor().equals(sendUserID)) {
				sendUserType = 1;
				otherUserId = complaints.getOtherUsers();
			} else if (complaints.getOtherUsers().equals(sendUserID)) {
				sendUserType = 2;
				otherUserId = complaints.getSponsor();
			} else {
				//回复者为平台，修改申述状态为处理中
				//Usercomplaints complaints=this.userComplaintsService.get(complaintsId);
				if(complaints.getAppealsStatus()<2){
					//为等待处理或者协商中
					complaints.setAppealsStatus(2);
					this.userComplaintsService.save(complaints);
				}
				
				otherUserId = complaints.getOtherUsers() + "," + complaints.getSponsor();
			}
			
			Orderwhisperinformation info = new Orderwhisperinformation();
			info.setOrderId(complaints.getOrderId());
			Orderwhisperrelationship ship = this.shipService.get(orderWhisperInfoID);
			if(ship!=null){
				info.setOrderTypeMark(ship.getOrderTypeMark());
			}
			
			String drumNo = this.orderInfoServivce.getDrumNo(sendTime, orderWhisperInfoID);
			if (drumNo == null) {
				drumNo = "1";
			}
			
			info.setComplianceMark('0');
			info.setDrumNo(Integer.parseInt(drumNo) + 1);
			info.setTextContent(textContent);
			info.setSendUserType(sendUserType);
			OrderwhisperinformationId id = new OrderwhisperinformationId(orderWhisperInfoID, new Date(System.currentTimeMillis()), sendUserID);
			info.setId(id);
			this.orderInfoServivce.save(info);

			String no = this.userMessageService.getMsgNo(sendTime);
			if (no == null) {
				no = "1";
			}
			int msgNo = Integer.parseInt(no);
			sendTime = sendTime.replace("-", "");
			for (String s : StringUtils.split(otherUserId, ",")) {
				Usermessages message = new Usermessages();
				Date time = new Date(System.currentTimeMillis());
				message.setMsgNo(msgNo++);
				message.setUserId(s);
				if ("1".equals(sendUserType)) {
					message.setUserType('2');

				} else if ("2".equals(sendUserType)) {
					message.setUserType('1');
				} else {
					message.setUserType('3');
				}
				message.setMessageId(sendTime + message.getMsgNo());
				message.setMessageContent(textContent);
				message.setSendTime(time);
				message.setMsgType(CommonConstant.MESSAGE_TYPE.complaints.getId());
				message.setMsgTitle("投诉回复消息");
				message.setPublisherType((char) (sendUserType + '0'));
				message.setPublisher(UserInfoCache.getCurrentUser().getUserId());
				message.setMsgStatus('0');// 未读
				message.setPublisherType('0');
				message.setAssociationId(info.getId().getOrderWhisperInfoId());
				this.userMessageService.save(message);
			}
			backstagelogService.log("043", complaints.getOrderId(), true);
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("新增申述聊天内容", e);
			backstagelogService.log("043", complaints.getOrderId(), false);
			return new Result<Object>(false, "操作失败");
		}

		return new Result<Object>(true, "操作成功");
	}
}
